<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <div class="content-box">
      <a-tabs v-model:activeKey="currentTab">
        <a-tab-pane v-for="item in tabData" :key="item.itemCode" :tab="item.itemName"></a-tab-pane>
        <template #rightExtra>
          <!-- <a-date-picker v-model:value="year" /> -->
          <a-range-picker  v-model:value="year2"
            format='YYYY-MM-DD' />
          <a-button type="primary" @click="updateList" :loading="exportLoading">同步</a-button>

        </template>
      </a-tabs>

      <div class="chart-box">
        <div v-if="currentTab == chart">
          <Detail :chart="chart"></Detail>
        </div>
        <BasicTable v-else @register="registerTable" :showIndexColumn="false" @change="tableChange">
          <template #toolbar>
            <!-- <a-button type="primary" @click="modelImport">下载模板</a-button>
            <BasicUploadModal @update:value="handleUpdateValue" title="导入数据" :api="postNatrualFileImport" :maxSize="20"
              class="inline" :maxNumber="10" :accept="['.xls', '.xlsx']" /> -->
            <a-button type="primary" @click="handleCreate">新增数据</a-button>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction :actions="createActions(record)" />
            </template>
          </template>
        </BasicTable>
      </div>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import Detail from './Detail.vue'
import { onMounted, ref, watch, unref, reactive, nextTick } from 'vue'
import { PageWrapper } from '@/components/Page'
import { BasicColumn, BasicTable, EditRecordRow, TableAction, useTable } from '@/components/Table'
import { getDictListByCode } from '@/api/sys/dict'
import {
  getNaturalTableHeader,
  getNaturalDelete,
  postNaturalTableData,
  postAddOrUpdateNaturalTableRecord,
  postNatrualFileImport,
  getNaturalExportTemplate,
  getGasplanNumDataSyn
} from '@/api/power/airConditioning/dailyUsage'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicUploadModal } from '@/components/Upload';
import { debounce } from 'lodash-es'
import { downloadByData, extractFileNameFromContentDisposition } from '@/utils/file/download'

type IRecord = {
  date: string;
  [key: string]: any;
}

type ITabData = {
  itemCode: string;
  itemName: string;
}

type IHeaderData = {
  [key: string]: number
}

type IColumnsData = {
  value: string;
  label: string;
  children?: IColumnsData[];
  [key: string]: any;
}

type FilterableObject = Record<string, string | number>;

// 字典的描述需要加上前缀 '废气化学品_', 后面跟上系统名称，如 '废气化学品_氢氧化钠'。便于后端导入时识别
defineOptions({ name: 'WasteGas' })

const { createMessage: msg } = useMessage();

const dictCode = 'energy_consumption_of_gas_consumption';
const chart = 'energy_consumption_of_gas_consumption_chart'
const tabData = ref<ITabData[]>([])
const currentTab = ref()
const dynamicColumns = ref<BasicColumn[]>([]);
const searchInfo = reactive<any>({})
const dynamicDataSource = ref<IRecord[]>([])
const currentEditKeyRef = ref('');
const sumChildrenItem = ref<IHeaderData>({})
const year2 = ref<dayjs[]>([dayjs(), dayjs()])

const [registerTable, { setPagination }] = useTable({
  title: '天然气用量统计',
  dataSource: dynamicDataSource,
  columns: dynamicColumns,
  bordered: true,
  actionColumn: {
    width: 100,
    title: '操作',
    dataIndex: 'action',
  },
});

const updateList = () => {
  const [startTime, endTime] = year2.value;
  const formattedStart = startTime.format('YYYY-MM-DD'); // 格式化为 'YYYY-MM-DD'
  const formattedEnd = endTime.format('YYYY-MM-DD');
  // exportLoading.value = true
  console.log(formattedStart, formattedEnd);
  getGasplanNumDataSyn({ startDate: formattedStart, endDate: formattedEnd, planNum: "" })
}

const modelImport = async () => {
  const ret = await getNaturalExportTemplate();
  const fileName = extractFileNameFromContentDisposition(ret.headers['content-disposition']) as string;
  downloadByData(ret.data, fileName);
}

// 没有使用api自动调用方式，需要手动配置分页
function tableChange(params: { current: number, pageSize: number }) {
  initialData(params.current, params.pageSize)
}

// 在表头中新增数据，不编辑其余字段，该条数据不会保存到数据库
const handleCreate = () => {
  // 新增数据时，默认赋值当前的日期，其他数据需要填写
  const newRecord: IRecord = { date: dayjs().format('YYYY-MM-DD'), key: Math.random().toFixed(10) }
  dynamicDataSource.value.unshift(newRecord)
  nextTick(() => {
    // 强制更新视图
    dynamicDataSource.value = [...dynamicDataSource.value];
  });
}

function handleEdit(record: EditRecordRow) {
  currentEditKeyRef.value = record.key;
  record.onEdit?.(true);
}

function handleCancel(record: EditRecordRow) {
  currentEditKeyRef.value = '';
  record.onEdit?.(false, false);
}

function filterObject(obj: FilterableObject): FilterableObject {
  const result: FilterableObject = {};
  for (const key in obj) {
    const value = obj[key];
    if (typeof value === "string" || typeof value === "number") {
      result[key] = value;
    }
  }
  return result;
}

const getSumValue = (rec) => {
  console.log('rec', rec)
  const sumIDs = Object.keys(sumChildrenItem.value);
  let sumValue = 0;
  sumIDs.forEach((id) => {
    sumValue += +rec[id] || 0;
  });
  return sumValue;
}

async function handleSave(record: EditRecordRow) {
  const filterRecord = filterObject(record)
  const recordCopy = Object.assign({}, filterRecord)
  const sumValue = getSumValue(recordCopy)
  // const todayUsage = getTodayUsage(filterRecord)
  const res = await postAddOrUpdateNaturalTableRecord({
    data: [{ ...filterRecord, dailyConsumption: sumValue }],
    classifyId: currentTab.value,
    id: record?.id ?? undefined
  })
  record.onEdit?.(false, false);
  // res不存在，标识保存成功。失败时data中会有错误提示
  if (!res) {
    msg.info(record?.id ? '数据更新成功' : '数据保存成功!')
    resetDataStatus()
  }
}

async function handleDelete(record: EditRecordRow) {
  if (record.id) {
    const res = await getNaturalDelete({ id: record.id })
    if (!res) {
      msg.info('删除成功!')
      resetDataStatus()
    }
  } else {
    // 新增了数据没有编辑保存，直接做了删除，自动重置状态
    resetDataStatus()
  }
}

const initialData = async (pageNo, pageSize) => {
  const res = await postNaturalTableData({
    classifyId: currentTab.value,
    pageNo,
    pageSize,
  });
  dynamicDataSource.value = res?.records;
  setPagination({
    current: pageNo,
    total: res.total ?? 0,
  })
}

// 初始化tab标签数据
const getTabData = async () => {
  const res = await getDictListByCode(dictCode);
  tabData.value = [
    ...res, // 后端返回的 Tab 数据
    { itemCode: chart, itemName: ' 天然气用量图' } // 新增的写死 Tab
  ];
  currentTab.value = res[0]?.itemCode
  searchInfo.classifyId = res[0].itemCode

}

// 监听tab页的切换，做两件事，一个是重组表头，一个是获取数据
watch([() => unref(currentTab)], () => {
  if (currentTab.value) {
    dynamicDataSource.value = []; // 重置数据
    sumChildrenItem.value = {}; // 重置总和
    getChemicalHeader(); // 重新加载表头
    resetDataStatus(); // 重新加载数据
  }
})

const handleUpdateValue = (value: any) => {
  resetDataStatus();
};

// 重置状态
const resetDataStatus = () => {
  initialData(1, 20)
  currentEditKeyRef.value = '';
}

function getTodayUsage(rec, v1) {
  const yesterday = dayjs(rec.date).subtract(1, 'day').format('YYYY-MM-DD');
  const yesterdayData = dynamicDataSource.value.find((item) => item.date === yesterday);
  rec[v1.value] = rec[v1.value] | 0;
  // 如果没有昨天的数据，直接返回
  if (!yesterdayData) {
    return rec[v1.value];
  }
  yesterdayData[v1.value] = yesterdayData[v1.value] | 0;
  return rec[v1.value] - yesterdayData[v1.value];
}

// 页面编辑时使用lodash的debounce函数，延迟1秒执行
const debouncedUpdate = debounce((opt, v1) => {
  // console.log('opt', opt, v1)
  const recCopy = Object.assign({}, opt.record)
  const todayUsage = getTodayUsage(recCopy, v1)
  opt.record[v1.target] = todayUsage;
  // opt.record['dailyConsumption'] = sum(Object.values(sumChildrenItem.value));
}, 1000);

// 重组表头数据
const getChemicalHeader = async () => {
  const originalColumns: any[] = [];
  const res = await getNaturalTableHeader({ parentClassifyId: currentTab.value }) as IColumnsData;
  // 将对象转成columns 数组
  for (let [_, v] of Object.entries(res)) {
    if (v.sum) {
      v.sum.forEach((item) => {
        sumChildrenItem.value[item] = 0;
      })
    }
    const comp = v.value == 'date' ? { // 日期类型
      editRow: true,
      editComponent: 'DatePicker',
      editComponentProps: {
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD',
      },
    } : v.time ? { // 登表时间
      editRow: true,
      editComponent: 'TimePicker',
      editComponentProps: {
        valueFormat: 'HH:mm',
        format: 'HH:mm',
      },
    } : { // 其他为数字类型
      editRow: false,
      editComponent: 'Input',
      editComponentProps: {
        // precision: 2,
        // step: 1,
        // min: 0,
      },
    }
    const newColumn: any = {
      title: v.label,
      dataIndex: v.value,
      width: 120,
      ...comp,
    }
    // 如果有children 遍历生成子列
    if (v.children) {
      const childrenColumns: BasicColumn[] = []
      for (let [_, v1] of Object.entries(v.children) as any) {
        const newChildrenColumn: BasicColumn = {
          title: v1.label,
          dataIndex: v1.value,
          editRow: v1.flag ? false : true,
          width: 120,
          editComponent: 'InputNumber',
          editComponentProps: (opt) => {
            if (v1.target) {
              debouncedUpdate(opt, v1);
            }
            return {
              precision: 4,
              step: 1,
              // min: 0,
            }
          },
        }
        childrenColumns.push(newChildrenColumn)
      }
      newColumn.children = childrenColumns
    }
    originalColumns.push(newColumn)
  }
  dynamicColumns.value = originalColumns;
}

function createActions(record) {
  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否取消删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      popConfirm: {
        title: '是否取消编辑',
        confirm: handleCancel.bind(null, record),
      },
    },
  ];
}

onMounted(() => {
  getTabData()
})

</script>

<style lang="less" scoped>
.content-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 8px;
  background: #fff;

  .header-select {
    width: 185px;
  }

  .chart-box {
    overflow: hidden;
  }

}
</style>
